package com.ruoyi.system.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Enumeration;

public class HttpHelper {
    public static String getBodyString(HttpServletRequest request) throws IOException {
        StringBuilder sb = new StringBuilder();
        InputStream inputStream = null;
        BufferedReader reader = null;
        try {
            inputStream = request.getInputStream();
            reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
            String line = "";
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }
    public static JSONObject getJSONObjectByMultiRequest(HttpServletRequest request, Integer isCutFirstObject){
        JSONObject res=null;
        if(request instanceof StandardMultipartHttpServletRequest){
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Enumeration<String> strings= multipartRequest.getParameterNames();
            res=new JSONObject();
            while (strings.hasMoreElements()){
                String string=strings.nextElement();
                String v=multipartRequest.getParameter(string);
                if(v.indexOf("{")>-1){
                    res.put(string, JSON.parseObject(v));
                }else if(v.indexOf("[")>-1){
                    res.put(string, JSON.parseArray(v));
                }else{
                    res.put(string,v);
                }
            }
        }
        if(isCutFirstObject==1){
            for(String key:res.keySet()){
                JSONObject object=res.getJSONObject(key);
                res=object;
                break;
            }
        }
        return res;
    }
}
